package com.up4years.controller.system;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;
import com.up4years.controller.base.BaseController;
import com.up4years.dataapi.service.system.UserService;
@Controller
@RequestMapping("/login")
public class LoginController extends BaseController {
	@Autowired
	private UserService userService;
	
	@RequestMapping("/in.htm")
	public String in(HttpServletRequest request){	
		return "/login/in";
	}
	@RequestMapping("/out.htm")
	public String out(HttpServletRequest request){	
		request.getSession(true).removeAttribute("currentUser");
		return "/login/in";
	}
	@RequestMapping("/signin.htm")
	public ModelAndView signin(String phone,String passwd,HttpServletRequest request){
		if(StringUtils.isBlank(phone)){
			 return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("用户名或手机号不可为空！", BaseController.RESCODE_FAIL));
		}
		if(StringUtils.isBlank(passwd)){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("密码不可为空！", BaseController.RESCODE_FAIL)); 
		}
		if(phone.length()>64){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("用户名或手机号位数过长！", BaseController.RESCODE_FAIL)); 
		}
		if(passwd.length()>128){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("密码位数过长！", BaseController.RESCODE_FAIL)); 
		}
		
		UsernamePasswordToken token = new UsernamePasswordToken(phone, passwd);
		Subject currentUser = SecurityUtils.getSubject();
		try{
			currentUser.login(token);
		}catch(UnknownAccountException e1){
 			currentUser.logout();
 			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("用户名/手机号/密码错误！", BaseController.RESCODE_FAIL));
 		}catch(IncorrectCredentialsException e2){
 			currentUser.logout();
 			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("用户名/手机号/密码错误！", BaseController.RESCODE_FAIL));
 		}
	    return new ModelAndView(new MappingJacksonJsonView(),this.getSuccessResult());
	}
}
